package com.gali.juc;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: gali
 * @Date: 2022-08-24 20:26
 * @Description:
 */
class House{
    int saleCount=0;
    public synchronized void saleHouse(){
        saleCount++;
    }
//    ThreadLocal<Integer> saleVolume=new ThreadLocal<Integer>(){
//        @Override
//        protected Integer initialValue() {
//            return 0;
//        }
//    };
    ThreadLocal<Integer> saleVolume=ThreadLocal.withInitial(()->0);
    public void saleVolumeThreadLocal(){
        saleVolume.set(1+saleVolume.get());
    }
}
public class ThreadLocalDemo {
    public static void main(String[] args) {
        House house = new House();
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                int size = new Random().nextInt(5)+1;
                try {
                    for (int j = 0; j < size; j++) {
                        house.saleHouse();
                        house.saleVolumeThreadLocal();
                    }
                    System.out.println(Thread.currentThread().getName()+"\t 号销售的套数为："+house.saleVolume.get());
                } finally {
                        house.saleVolume.remove();
                }
            },String.valueOf(i)).start();
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"\t 销售的总套数为："+house.saleCount);
    }
}
